import SongList from '@/components/Base/SongList/SongList'
import Scroll from '@/components/Base/ScrollContainer'
import { useStore, mapActions } from 'vuex'
import { computed } from 'vue'
import { getObj } from '@/assets/js/sessionStore'

const IMG_HEADER_HEIGHT = 40

function createDetailComponent(name, key) {
  return {
    name,
    components: {
      SongList,
      Scroll
    },
    props: {
      musicList: {
        required: true,
        type: Array
      }
    },
    setup() {
      const { state } = useStore()
      const playList = computed(() => {
        return state.play.playList
      })
      return {
        playList
      }
    },
    data() {
      return {
        imgHeight: 0,
        zIndex: 0,
        posY: 0,
        singer: {},
        textVisible: true
      }
    },
    computed: {
      coverStyle() {
        const pic = this.singer.pic
        let zIndex = this.zIndex
        const posY = this.posY
        let scale = 1
        if (posY < 0) {
          scale = this.calculateScale(posY)
          zIndex = 2
        } else {
          scale = 1
        }
        return {
          backgroundImage: `url(${pic})`,
          backgroundSize: 'cover',
          height: zIndex > 0 && scale === 1 ? `${IMG_HEADER_HEIGHT}px` : 0,
          paddingTop: zIndex > 0 && scale === 1 ? '0' : '70%',
          zIndex,
          transform: `scale(${scale}) translateZ(1px)`
        }
      },
      songListStyle() {
        return {
          top: `${this.imgHeight}px`,
          bottom: this.playList.length === 0 ? 0 : '60px'
        }
      }
    },
    created() {
      this.singer = getObj(key)
    },
    mounted() {
      this.imgHeight = this.$refs.img.offsetHeight
    },
    methods: {
      ...mapActions({
        selectPlay: 'play/selectPlay',
        randomPlay: 'play/randomPlay'
      }),
      onScroll(posY) {
        this.posY = posY
        const d = this.imgHeight - posY
        if (d <= IMG_HEADER_HEIGHT) {
          this.zIndex = 2
          this.textVisible = false
        } else {
          this.zIndex = 0
          this.textVisible = true
        }
      },

      calculateScale(posY) {
        const y = -posY
        const MAX_DISTANCE = 100
        const MAX_SCALE = 0.5
        // 100/0.5 = y/x
        return (MAX_SCALE * y) / MAX_DISTANCE + 1
      },

      selectItem({ song, index }) {
        this.selectPlay({
          list: this.musicList,
          index
        })
      },

      // 洗牌
      clickRandom() {
        this.randomPlay(this.musicList)
      }
    }
  }
}

export default createDetailComponent
